package com.tg.loginex.helper;

import android.app.Activity;
import android.content.Context;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import androidx.core.text.HtmlCompat;
import com.appbase.custom.constant.CommonConstants;
import com.tg.appcommon.android.ClickableSpanHelper;
import com.tange.base.toolkit.PreferenceUtil;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGAlertDialog;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.business.ILoginModule;
import com.tg.appcommon.router.TGBusiness;
import com.tg.loginex.R;

public class UserProtocolHelper {
    public void userProtocol(Activity activity, Runnable agreeRunnable) {
        boolean isAgree = isAgreeProtocol(activity);
        if (isAgree){
            // do nothing
        }else {
            showProtocol(activity, agreeRunnable);
        }
    }

    public static boolean isAgreeProtocol(Context context) {
        return PreferenceUtil.getBoolean(context, CommonConstants.PRE_PROTOCOL);
    }

    private void showProtocol(Activity activity, Runnable agreeRunnable){
        TGAlertDialog dialog = new TGAlertDialog(activity);
        String p = ResourcesUtil.getResources().getString(R.string.protocol_content);
        Spanned protocol = HtmlCompat.fromHtml(p,HtmlCompat.FROM_HTML_MODE_LEGACY);
        dialog.builder().setTitle(R.string.protocol);
        dialog.getMessageTextView().setAutoLinkMask(Linkify.WEB_URLS);
        dialog.getMessageTextView().setMovementMethod(LinkMovementMethod.getInstance());
        dialog.setMessage(ClickableSpanHelper.getClickableHtml(activity, protocol));
        dialog.setPositiveButton(R.string.agree, view -> {
            PreferenceUtil.setBoolean(activity,CommonConstants.PRE_PROTOCOL,true);
            ILoginModule iLoginModule = TGBusiness.getLoginModule();
            iLoginModule.agreeProtocol(activity);
            if (agreeRunnable != null) {
                agreeRunnable.run();
            }
        }).setNegativeButton(R.string.refuse, v -> {
            TGApplicationBase.getInstance().finishAllActivity();
            System.exit(0);
        });
        dialog.setCancelable(false);
        dialog.show();
    }
}
